<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 10:46
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class DemoPlay extends Model
{
    protected $table = 'task_test_log';
    protected $guarded = [];

    //判断是否第一次试玩 是加金币
    public function addTaskLog($task_id, $member_id){
        $model = DemoPlay::select()
            ->where(['task_id' => $task_id, 'member_id' =>$member_id])
            ->first();
        try{
            DB::beginTransaction();
            $task_test = TaskTest::select('bi', 'play_nums')
                ->where('id', $task_id)
                ->first();
            if(!$task_test){
                return ['msg' => '无效试玩任务id', 'code' => 0];
            }
            //更改试玩任务试玩次数
            $task_update = [
                'play_nums' => $task_test['play_nums'] + 1,
            ];
            TaskTest::where('id', $task_id)->update($task_update);
            if(!$model){
                //添加试玩记录
                $insert = [
                    'task_balance' => $task_test['bi'],
                    'task_id' => $task_id,
                    'member_id' => $member_id
                ];
                DemoPlay::create($insert); //保护机制
                //更改用户金币余额
                $sql = Member::select('bi')->where('id', $member_id)->first();
                $member_update = [
                    'bi' => $sql['bi'] + $task_test['bi'],
                ];
                Member::where('id', $member_id)->update($member_update);
                //添加流水记录
                $capital = [
                    'from_source' => getIp(),
                    'member_id' => $member_id,
                    'money' => $task_test['bi'],
                    'type_test_id' => $task_id,
                    'bei' => '试玩任务' . $task_id . '奖励[' . $task_test['bi'] . ']金币',
                    'date' => date('Y-m-d')
                ];
                $info = CapitalLog::create($capital);
                if($info) {
                    $result['msg'] = '金币添加成功';
                    $result['code'] = 1;
                }else{
                    $result['msg'] = '金币添加失败';
                    $result['code'] = 0;
                }
            }else{
                $result['msg'] = '试玩次数更新成功';
                $result['code'] = 1;
            }
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            $result['msg'] = '操作失败';
            $result['code'] = 0;
        }
        return $result;
    }
}
